#!/bin/bash

#PATH=$PATH:./build-root/build-vpp-native/vpp/bin/
PATH=$PATH:./build-root/install-vpp_debug-native/vpp/bin/
if [ $USER != "root" ] ; then
    echo "Restarting script with sudo..."
    sudo $0 ${*}
    exit
fi

# delete previous incarnations if they exist
ip link del dev vpp1
ip link del dev vpp2
ip netns del vpp1

#create namespaces
ip netns add vpp1

# create and configure 1st veth pair
ip link add name veth_vpp1 type veth peer name vpp1
ip link set dev vpp1 up
ip link set dev veth_vpp1 up netns vpp1

ip netns exec vpp1 \
  bash -c "
    ip link set dev lo up
    ip addr add 172.16.1.2/24 dev veth_vpp1
    ip route add 172.16.2.0/24 via 172.16.1.1
    ip route add default via 172.16.1.1
"

# create and configure 2nd veth pair
ip link add name veth_vpp2 type veth peer name vpp2
ip link set dev vpp2 up
ip addr add 172.16.2.2/24 dev veth_vpp2
ip link set dev veth_vpp2 up
ip route add 172.16.1.0/24 via 172.16.2.2

# configure VPP
vppctl create host-interface name vpp1
vppctl create host-interface name vpp2
vppctl set int state host-vpp1 up
vppctl set int state host-vpp2 up
vppctl set int ip address host-vpp1 172.16.1.1/24
vppctl set int ip address host-vpp2 172.16.2.1/24
vppctl ip route add 172.16.1.0/24 via 172.16.1.1 host-vpp1
vppctl ip route add 172.16.2.0/24 via 172.16.2.1 host-vpp2
vppctl ip route add 0.0.0.0/0 via 172.16.2.2 host-vpp2
vppctl set interface proxy-arp host-vpp2 enable
vppctl set ip arp proxy 172.16.1.1 - 172.16.1.2

# Enable IP-forwarding.
echo 1 > /proc/sys/net/ipv4/ip_forward

# Flush forward rules.
iptables -P FORWARD DROP
iptables -F FORWARD
 
# Flush nat rules.
iptables -t nat -F

# Enable NAT masquerading
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
 
iptables -A FORWARD -i wlan0 -o veth_vpp2 -j ACCEPT
iptables -A FORWARD -o wlan0 -i veth_vpp2 -j ACCEPT
